package com.examples.util;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.CharUtils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class IsvProduceAPI {
    /**
     * 默认编码：UTF-8
     */
    private static final String CHARSET = "UTF-8";

    /**
     * 获取请求体签名
     *
     * @param key  accessKey
     * @param body 待签名的body体字符串
     * @return 生成的签名
     */
    public static String generateSignature(String key, String body) {
        return Hex.encodeHexString(hmacSHA256(key, body));
    }

    public static byte[] hmacSHA256(String macKey, String macData) {
        try {
            SecretKeySpec secret = new SecretKeySpec(macKey.getBytes(CHARSET), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(secret);
            return mac.doFinal(macData.getBytes(CHARSET));
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            // error message log
            throw new CustomException(ResultCodeEnum.INVALID_PARAM.getResultCode(), "encrypt sign failed.");
        }
    }

    public static String toUnicodeString(String string) {
        StringBuilder unicode = new StringBuilder();
        for (int i = 0; i < string.length(); i++) {
            // 取出每一个字符
            char c = string.charAt(i);
            // 转换为unicode
            unicode.append(!CharUtils.isAsciiPrintable(c) ? "\\u" + Integer.toHexString(c) : c);
        }
        return unicode.toString();
    }
}
